package com.pc.scrs.service.impl;

import com.pc.scrs.bean.po.Perms;
import com.pc.scrs.dao.PermsDao;
import com.pc.scrs.service.IPermsService;
import com.pc.scrs.utils.JwtUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class PermsService implements IPermsService {

    @Resource
    private PermsDao permsDao;

    @Override
    public List<Perms> selectPermsByUserName(String jwtToken) {
        String username = JwtUtils.getUserNameFormJwt(jwtToken);
        //获取数据库中的菜单数据
        List<Perms> permsList = permsDao.getPermsByRoleId(permsDao.selectRoleIdByUserName(username));

        List<Perms> parentList = new ArrayList<>();
        //有值，获取父级菜单
        if (permsList != null && permsList.size() > 0) {
            //获得父菜单
            for (Perms parent : permsList) {
                if (parent.getParentId() == null) {
                    parentList.add(parent);
                }
            }
            //循环获得子菜单集合
            //循环所有菜单
            for (Perms p : parentList) {
                List<Perms> childrenList = new ArrayList<>();
                //获得子菜单
                //循环子菜单根据条件判断并加入子菜单集合
                for (Perms children : permsList) {
                    if (children.getParentId() == p.getId()) {
                        childrenList.add(children);
                    }
                }
                //将子菜单集合加入父菜单对象集合属性中
                p.setChildrenMenu(childrenList);
            }
        }
        return parentList;
    }
}
